package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.UserMapper;
import com.styletransfer.model.ApiResponse;
import com.styletransfer.model.PageRequest;
import com.styletransfer.model.PageResponse;
import com.styletransfer.model.User;
import com.styletransfer.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务类
 *
 * 这个类负责处理与用户相关的业务逻辑，包括用户注册、登录、信息更新等。
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     *
     * @param user 用户对象
     * @return API响应
     */
    public ApiResponse<Map<String, Object>> register(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (user.getEmail() != null && !user.getEmail().isEmpty() && userMapper.findByEmail(user.getEmail()) != null) {
            throw new BusinessException("邮箱已被注册");
        }

        // 设置默认值
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setStatus(1); // 1:正常, 0:禁用
        user.setRole("user"); // 默认角色为普通用户

        // 如果没有设置昵称，则使用用户名作为昵称
        if (user.getNickname() == null || user.getNickname().isEmpty()) {
            user.setNickname(user.getUsername());
        }

        // 如果没有设置头像，则使用默认头像
        if (user.getAvatar() == null || user.getAvatar().isEmpty()) {
            user.setAvatar("https://picsum.photos/300/400?random=10");
        }

        // 插入用户
        userMapper.insert(user);

        // 生成JWT令牌，包含用户ID
        String token = jwtUtil.generateToken(user.getUsername(), user.getId());

        // 构建响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);

        return ApiResponse.success(data);
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return API响应
     */
    public ApiResponse<Map<String, Object>> login(String username, String password) {
        try {
            // 认证用户
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );

            // 设置认证信息到上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取用户信息
            User user = userMapper.findByUsername(username);

            // 生成JWT令牌，包含用户ID
            String token = jwtUtil.generateToken(username, user.getId());

            // 构建响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);

            return ApiResponse.success(data);
        } catch (Exception e) {
            throw new BusinessException("用户名或密码错误");
        }
    }

    /**
     * 获取当前登录用户信息
     *
     * @return API响应
     */
    public ApiResponse<User> getCurrentUser() {
        // 获取当前认证用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 查询用户信息
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        return ApiResponse.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return API响应
     */
    public ApiResponse<User> updateUser(User user) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userMapper.findByUsername(username);

        // 检查是否为当前用户
        if (!currentUser.getId().equals(user.getId())) {
            throw new BusinessException("只能修改自己的信息");
        }

        // 设置不可修改的字段
        user.setUsername(currentUser.getUsername());
        user.setPassword(currentUser.getPassword());
        user.setCreateTime(currentUser.getCreateTime());
        user.setStatus(currentUser.getStatus());
        user.setRole(currentUser.getRole());
        user.setUpdateTime(new Date());

        // 更新用户信息
        userMapper.update(user);

        return ApiResponse.success(user);
    }

    /**
     * 修改密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return API响应
     */
    public ApiResponse<Void> changePassword(String oldPassword, String newPassword) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userMapper.findByUsername(username);

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new BusinessException("旧密码错误");
        }

        // 更新密码
        userMapper.updatePassword(user.getId(), passwordEncoder.encode(newPassword));

        return ApiResponse.success();
    }

    /**
     * 分页查询用户
     *
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<User> findByPage(PageRequest pageRequest) {
        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<User> users = userMapper.findByPage(offset, pageRequest.getPageSize());
        Long total = userMapper.count();

        // 构建分页响应
        return new PageResponse<>(users, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }

    /**
     * 根据ID查询用户
     *
     * @param id 用户ID
     * @return API响应
     */
    public ApiResponse<User> findById(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        return ApiResponse.success(user);
    }

    /**
     * 更新用户状态（管理员操作）
     *
     * @param id 用户ID
     * @param status 新状态
     * @return API响应
     */
    public ApiResponse<Void> updateStatus(Long id, Integer status) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userMapper.findByUsername(username);

        // 检查是否为管理员
        if (!"admin".equals(currentUser.getRole())) {
            throw new BusinessException("没有权限执行此操作");
        }

        // 检查用户是否存在
        User user = userMapper.findById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 不能修改管理员状态
        if ("admin".equals(user.getRole())) {
            throw new BusinessException("不能修改管理员状态");
        }

        // 更新状态
        userMapper.updateStatus(id, status);

        return ApiResponse.success();
    }

    /**
     * 搜索用户（管理员功能）
     *
     * @param keyword 关键词
     * @return API响应
     */
    public ApiResponse<List<User>> searchUsers(String keyword) {
        // 检查当前用户是否为管理员
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))) {
            throw new BusinessException("无权限执行此操作");
        }

        // 搜索用户
        List<User> users = userMapper.search(keyword);

        return ApiResponse.success(users);
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    public Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }

}
